package com.aspectj.aop.aspects;

import android.widget.Toast;

import com.aspectj.aop.annotation.RequirePermission;
import com.aspectj.aop.root.AndroidAOP;
import com.aspectj.aop.utils.PermissionUtils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * desc   : 权限AOP
 * author : chendaning
 * date   : 6/11/21
 */
@Aspect
public class PermissionAspect extends FatherAspect{
    private final String POINTCUT = "execution(@com.aspectj.aop.annotation.RequirePermission * *(..))";

    @Pointcut(POINTCUT)
    public void onPermissionPointcut() {}

    /**
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("onPermissionPointcut() && @annotation(permission)")
    public void execute(ProceedingJoinPoint joinPoint, RequirePermission permission) throws Throwable {
        if(permission.value() == null || permission.value().length == 0) {
            throw new Exception("请设置要申请的权限！");
        }
        logger("inter permisson method");
        PermissionUtils.requestPermissionNow(permission.value(), new PermissionUtils.OnPermissionResult() {
            @Override
            public void onRequestSuccess() {
                logger("onRequestSuccess now");
                try {
                    joinPoint.proceed();
                } catch (Throwable e) {
                    logger("onRequestSuccess ERROR=" + e.toString());
                }
            }

            @Override
            public void onRequestDenied() {
                logger("onRequestDenied now");
                Toast.makeText(AndroidAOP.getmContext(), "权限用户选择了禁止", Toast.LENGTH_SHORT).show();
            }
        });
    }

}